package com.zh.yida.controller;

import com.zh.yida.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * 图片上传下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${yida.file}")
    private String localPath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        if (!file.isEmpty()) {
            String uuid = UUID.randomUUID().toString() + "." + file.getContentType().split("/")[1];
            String url = localPath + "/" + uuid;
            try {
                file.transferTo(new File(url));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return R.success(uuid);
        }
        return R.error("出错了");
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(new File(localPath + "/" + name)));
            bos = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
